package com.mv.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mv.mapper.*;
import com.mv.pojo.*;
import com.mv.vo.MovieRecord;
import com.mv.vo.Record;
import com.mv.vo.Select;
import com.mv.vo.UserRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class DealServiceImpl implements DealService{
    private static Deal deal;
    private static Consume consume;
    private static Recharge recharge;
    @Autowired
    private UserService userService;
    @Autowired
    private ExchangeMapper exchangeMapper;
    @Autowired
    private ExchangeService exchangeService;
    @Autowired
    private ConsumeService consumeService;
    @Autowired
    private CardService cardService;
    @Autowired
    private DealService dealService;
    @Autowired
    private DealMapper dealMapper;
    @Autowired
    private CardMapper cardMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MovieMapper movieMapper;
    @Autowired
    private RechargeMapper rechargeMapper;
    @Autowired
    private ConsumeMapper consumeMapper;
    @Autowired
    private DealRecordMapper dealRecordMapper;
    /*新增消费交易*/
    @Transactional
    @Override
    public void consumeDeal(Card card, Movie movie) {
        if(deal==null){
            synchronized (DealServiceImpl.class){
                if(deal==null){
                    deal=new Deal();
                }
            }
        }
        deal.setCardId(card.getId())
                .setTransaction(0)
                .setMoneyChange(movie.getPrice()*movie.getNum())
                .setIntegralChange(movie.getIntegral()*movie.getNum())
                .setDealTime(new Date());
        dealMapper.insert(deal);
        if(consume==null){
            synchronized (DealServiceImpl.class){
                if(consume==null){
                    consume=new Consume();
                }
            }
        }
        consume.setDealId(deal.getId()).setMovieId(movie.getId()).setNum(movie.getNum());
        consumeMapper.insert(consume);
    }
    /*新增充值交易*/
    @Transactional
    @Override
    public void rechargeDeal(Recharge recharge) {
        if(deal==null){
            synchronized (DealServiceImpl.class){
                if(deal==null){
                    deal=new Deal();
                }
            }
        }
        deal.setCardId(recharge.getCardId())
                .setTransaction(1)
                .setMoneyChange(recharge.getPrice())
                .setIntegralChange(0)
                .setDealTime(new Date());
        dealMapper.insert(deal);
        if(recharge==null){
            synchronized (DealServiceImpl.class){
                if(recharge==null){
                    recharge=new Recharge();
                }
            }
        }
        recharge.setDealId(deal.getId());
        rechargeMapper.insert(recharge);
    }
    /*根据会员卡ID获取交易记录*/
    @Override
    public List<Deal> getDealListByCardId(String cardId,String query,String mode) {
        if(query==null||"".equals(query)){
            Map<String,List<Deal>> map=getMapByCardId();
            return map.get(cardId);
        }
        ArrayList<Deal> deals = new ArrayList<>();
        Map<Integer, Deal> map = getMapById();
        QueryWrapper<Deal> queryWrapper = new QueryWrapper<>();
        if(mode=="id"){
            queryWrapper.eq("card_id", cardId).like("id", query);
        }else {
            queryWrapper.eq("card_id", cardId).like("deal_time", query);
        }
        List<Deal> dealList = dealMapper.selectList(queryWrapper);
        for (Deal deal : dealList) {
            Integer id = deal.getId();
            deals.add(map.get(id));
        }
        return deals;
    }
    /*根据会员卡ID删除交易记录*/
    @Transactional
    @Override
    public void deleteDeal(String cardId) {
        QueryWrapper<Deal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("card_id", cardId);
        dealMapper.delete(queryWrapper);
    }
    /*根据交易单号查询交易记录*/
    @Override
    public Deal getDealById(Integer id) {
        return dealMapper.selectById(id);
    }
    /*根据交易单号查询会员用户名*/
    @Override
    public String getUserNameById(Integer id) {
        Deal deal = dealService.getDealById(id);
        Card card = cardService.getCardById(deal.getCardId());
        return cardService.getUserNameByUserId(card.getUserId());
    }

    @Override
    public List<Deal> getRechargeList() {
        QueryWrapper<Deal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("transaction",1);
        List<Deal> dealList = dealMapper.selectList(queryWrapper);
        return dealList;
    }

    @Override
    public List<Select> getSelectList() {
        ArrayList<Select> selects = new ArrayList<>();
        List<Deal> dealList = getRechargeList();
        for (Deal deal : dealList) {
            Select select = new Select().setText(deal.getCardId()).setValue(deal.getCardId());
            if(!selects.contains(select)){
                selects.add(select);
            }
        }
        return selects;
    }

    @Override
    public List<Deal> getConsumeList() {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("transaction", 0 );
        List<Deal> dealList = dealMapper.selectList(queryWrapper);
        for (Deal deal : dealList) {
            queryWrapper.clear();
            queryWrapper.eq("deal_id", deal.getId());
            Consume consume = consumeMapper.selectOne(queryWrapper);
            queryWrapper.clear();
            String movieName = movieMapper.selectById(consume.getMovieId()).getName();
            deal.setNum(consume.getNum()).setMovieName(movieName);
        }
        return dealList;
    }

    @Override
    public Record getRecord() {
        /**交易金额占比*/
        Double moneySum=dealMapper.getMoneySum();
        Double consumeMoneySum=dealMapper.getConsumeMoneySum();
        int consume=(int) (consumeMoneySum * 100 / moneySum);
        int recharge=100-consume;
        Integer consumeIntegralSum=dealMapper.getConsumeIntegralSum();
        Integer exchangeIntegralSum=0;
        List<Exchange> exchangeList = exchangeService.getExchangeList();
        for (Exchange exchange : exchangeList) {
            List<Exchange> children = exchange.getChildren();
            for (Exchange child : children) {
                exchangeIntegralSum+=child.getIntegralChange();
            }
        }
        Integer integralSum=consumeIntegralSum+exchangeIntegralSum;
        int integral=exchangeIntegralSum*100/integralSum;
        /**成交率*/
        Integer integralDealSum = exchangeMapper.selectCount(null);
        Integer dealSum=dealMapper.selectCount(null)+integralDealSum;
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("transaction", 0);
        Integer consumeDealSum = dealMapper.selectCount(queryWrapper);
        Integer consumeDeal=consumeDealSum*100/dealSum;
        Integer integralDeal=integralDealSum*100/dealSum;
        Integer rechargeDeal=100-consumeDeal-integralDeal;
        /**传值*/
        Record record=new Record();
        record.setConsume(consume)
                .setRecharge(recharge)
                .setIntegral(integral)
                .setConsumeDeal(consumeDeal)
                .setRechargeDeal(rechargeDeal)
                .setIntegralDeal(integralDeal);
        return record;
    }

    @Override
    public List<UserRecord> getUserRecordList() {
        List<UserRecord> userRecordList=new ArrayList<>();
        List<User> userList = userService.getUserName();
        QueryWrapper<Deal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("transaction", 1);
        Integer rechargeDealSum = dealMapper.selectCount(queryWrapper);
        queryWrapper.clear();
        queryWrapper.eq("transaction", 0);
        Integer consumeDealSum = dealMapper.selectCount(queryWrapper);
        queryWrapper.clear();
        Double consumeMoneySum=dealMapper.getConsumeMoneySum();
        Double rechargeMoneySum=dealMapper.getRechargeMoneySum();
        Integer integralDealSum = exchangeMapper.selectCount(null);
        for (User user : userList) {
            List<String> cardList = cardService.getCardIdByUserId(user.getId());
            if(cardList==null||cardList.size()==0){
                continue;
            }
            Double consumeMoney= dealRecordMapper.getConsumeMoney(cardList);
            Double rechargeMoney= dealRecordMapper.getRechargeMoney(cardList);
            if(consumeMoney==null||rechargeMoney==null){
                rechargeMoney=0.00;
                consumeMoney=0.00;
            }
            int recharge= (int) (rechargeMoney*100/rechargeMoneySum);
            int consume= (int) (consumeMoney*100/consumeMoneySum);
            Integer consumeCount=dealRecordMapper.getConsumeCount(cardList);
            Integer rechargeCount=dealRecordMapper.getRechargeCount(cardList);
            Integer integralCount=dealRecordMapper.getIntegralCount(cardList);
            Integer rechargeDeal=rechargeCount*100/rechargeDealSum;
            Integer consumeDeal=consumeCount*100/consumeDealSum;
            Integer integralDeal=integralCount*100/integralDealSum;
            userRecordList.add(new UserRecord()
                    .setUserName(user.getUserName())
                    .setConsumeMoney(consumeMoney)
                    .setRechargeMoney(rechargeMoney)
                    .setConsumeDealCount(consumeCount)
                    .setRechargeDealCount(rechargeCount)
                    .setIntegralDealCount(integralCount)
                    .setConsume(consume)
                    .setRecharge(recharge)
                    .setIntegralDeal(integralDeal)
                    .setRechargeDeal(rechargeDeal)
                    .setConsumeDeal(consumeDeal));
        }
        return userRecordList;
    }
    /*获取所有交易记录*/
    @Override
    public List<Deal> getDealList(String query,String mode) {
        if(query==null||"".equals(query)){
            return findDealList();
        }
        List<Deal> deals = new ArrayList<>();
        Map<Integer, Deal> map = getMapById();
        QueryWrapper<Deal> queryWrapper = new QueryWrapper<>();
        if(mode.equals("id")){
            queryWrapper.like("id", query);
        }else{
            queryWrapper.like("deal_time", query);
        }
        List<Deal> dealList = dealMapper.selectList(queryWrapper);
        for (Deal deal : dealList) {
            Integer id = deal.getId();
            deals.add(map.get(id));
        }
        return deals;
    }
    /*key为id,封装map*/
    private Map<Integer, Deal> getMapById() {
        List<Deal> dealList = findDealList();
        Map<Integer, Deal> map=new HashMap<>();
        for (Deal deal : dealList) {
            Integer id = deal.getId();
            map.put(id,deal);
        }
        return map;
    }
    /*key为cardId,封装map*/
    private Map<String, List<Deal>> getMapByCardId() {
        List<Deal> dealList=findDealList();
        Map<String, List<Deal>> map=new HashMap<>();
        for (Deal deal : dealList) {
            String cardId = deal.getCardId();
            if(map.containsKey(cardId)){
                map.get(cardId).add(deal);
            }else {
                ArrayList<Deal> list = new ArrayList<>();
                list.add(deal);
                map.put(cardId,list);
            }
        }
        return map;
    }
    /*封装交易记录(包含充值和消费记录)*/
    private List<Deal> findDealList() {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        List<Deal> dealList = dealMapper.selectList(null);
        for (Deal deal : dealList) {
            String cardId = deal.getCardId();
            queryWrapper.eq("id", cardId);
            Card card = cardMapper.selectOne(queryWrapper);
            Integer userId = card.getUserId();
            queryWrapper.clear();
            queryWrapper.eq("id",userId);
            String userName = userMapper.selectOne(queryWrapper).getUserName();
            queryWrapper.clear();
            deal.setUserName(userName);
            Integer id = deal.getId();
            queryWrapper.eq("deal_id",id);
            if(deal.getTransaction()==1){
                Recharge recharge = rechargeMapper.selectOne(queryWrapper);
                recharge.setPrice(deal.getMoneyChange());
                deal.setRecharge(recharge);
            }
            if(deal.getTransaction()==0){
                Consume consume = consumeMapper.selectOne(queryWrapper);
                queryWrapper.clear();
                queryWrapper.eq("id", consume.getMovieId());
                Movie movie = movieMapper.selectOne(queryWrapper);
                consume.setMovieName(movie.getName())
                        .setPrice(deal.getMoneyChange()/consume.getNum())
                        .setIntegral(deal.getIntegralChange()/consume.getNum());
                deal.setConsume(consume);
            }
            queryWrapper.clear();
        }
        return dealList;
    }
}
